package com.tn.auth.config;

import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.catalina.Context;
import org.apache.catalina.Wrapper;
import org.springframework.boot.web.embedded.tomcat.TomcatContextCustomizer;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileNotFoundException;

@Slf4j
//@Component
public class FileIndex implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {
    @Override
    public void customize(TomcatServletWebServerFactory factory) {
        // customize the factory here
        TomcatContextCustomizer tomcatContextCustomizer = new TomcatContextCustomizer() {
            @Override
            public void customize(Context context) {
                String indexDir = "D:\\_own\\hgpHs\\tn_aucy_java\\logs";
                String parentFolder = indexDir.substring(0,indexDir.lastIndexOf("\\"));
                String childFolder = indexDir.substring(indexDir.lastIndexOf("\\") + 1);
                parentFolder = getJarPath();
                childFolder = "logs";
                log.info("要映射的目录是： {}, {}", parentFolder, childFolder);
                context.setDocBase(parentFolder);
                Wrapper defServlet = (Wrapper) context.findChild("default");
                if(defServlet == null) {
                    log.error("defServlet = null, 结束");
                } else {
                    defServlet.addInitParameter("listings", "true");
                    defServlet.addInitParameter("readOnly", "false");
                    defServlet.addMapping("/"+ childFolder + "/*");
                }
            }
        };
        factory.addContextCustomizers(tomcatContextCustomizer);
    }

    public static String getJarPath() {
        String jar_parent = null;
        try {
            jar_parent = new File(ResourceUtils.getURL("classpath:").getPath()).getParentFile().getParent();//.getParentFile().getParent();
        } catch (FileNotFoundException e) {
            log.error("getJarPath excepiton: {}", e);
        }
        return jar_parent;
    }
}
